/**
 *
 * @param obj
 * @param success_callback
 * @param error_callback
 * @returns {boolean}
 */
function save_form(obj,success_callback,error_callback){
    let action=$(obj).attr("action");
    let method=$(obj).attr("method");
    let data=$(obj).serializeArray();
    let more_pic = [];
    let newData = [];
    for (let i in data) {
        let name = data[i]['name'];
        let value = data[i]['value'];
        if(name.includes('_smallimg')){
            let arr = name.split('_smallimg');
            if(!more_pic[arr[0]]){
                more_pic[arr[0]] = [];
                more_pic[arr[0]]['small'] = [];
                more_pic[arr[0]]['big'] = [];
                more_pic[arr[0]]['name'] = [];
            }
            more_pic[arr[0]]['small'].push(value);
        }
        else if(name.includes('_bigimg')){
            let arr = name.split('_bigimg');
            more_pic[arr[0]]['big'].push(value);
        }
        else if(name.includes('_imgname')){
            let arr = name.split('_imgname');
            more_pic[arr[0]]['name'].push(value);
        }else {
            newData.push(data[i]);
        }
    }
    data = newData;
    if(more_pic) {
        for(let i in more_pic) {
            let code = '';
            for(let j in more_pic[i]['name']) {
                code += more_pic[i]['small'][j] + '||' +  more_pic[i]['big'][j] + '||' +  more_pic[i]['name'][j]  + "\r\n";
            }
            data.push({'name': i, 'value':code});
        }
    }
    for (let i in data) {
       // data[i]['value'] = encrypt(data[i]['value']);
    }
    //找到当前表单下的submit按钮，修改状态，并且把文字改为提交中
    $(obj).find("button[type='submit']").attr("disabled",true);
    let old_button_val=$(obj).find("button[type='submit']").html();
    $(obj).find("button[type='submit']").html("提交中...");
    //
    let index=layer.load(0,{time:100000});//加载气泡提示
    $.ajax({
        url:action,
        type:method,
        async:true,
        data:data,
        dataType:'json',
        success:function(result){
            let code=result.code;
            let msg=result.msg;
            let returndata=result.result;
            let url=result.url;
            if(code){
                if(success_callback){
                    success_callback(msg,returndata, url);//回调函数
                }else{
                    msg = msg === 'ok' ? '提交成功' : msg;
                    layer.msg(msg,{time:500},function(){
                        if(url){
                            window.location.href=url;
                        }else{
                            window.location.href=document.referrer;
                        }
                    });
                }
            }else{
                if(error_callback){
                    error_callback(msg, returndata, url);//回调函数
                }else{
                    parent.layer.alert(msg);
                }
                $(obj).find("button[type='submit']").attr("disabled",false);
                $(obj).find("button[type='submit']").html(old_button_val);
            }
        },
        error:function(xhr,textStatus){
            alert("程序出错，请联系管理员");
        },
        complete:function(){
            layer.close(index);//关闭加载气泡提示
            //5s以后再给消失，因为在页面跳转中浏览器可能需要等待
            setTimeout(function(){
                $(obj).find("button[type='submit']").attr("disabled",false);
                $(obj).find("button[type='submit']").html(old_button_val);
            },2000)
        }
    })
    return false;
}


function encrypt(str, key = 'ZZWBKJ_ZHIHUAWEI', iv = 'ZZWBKJ_ZHIHUAWEI') {
    //密钥16位
    key = CryptoJS.enc.Utf8.parse(key)
    iv = CryptoJS.enc.Utf8.parse(iv)
    const encryptedData = CryptoJS.AES.encrypt(str, key, {
        iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    })

    return encryptedData.toString() + '==s==';

}


function save_form2(obj){
    save_form(obj,function(msg,data,url){
        msg = msg === 'ok' ? '提交成功' : msg;
        layer.msg(msg, {time: 500}, function (){
            if(url){
                window.location.href=url;
            }else{
                parent.location.reload();
            }
        })
    });
    return false;
}


function ajax_del(ajax_url,success_callback,error_callback){
    let index=layer.load(0,{time:100000});//加载气泡提示
    $.ajax({
        url:ajax_url,
        type:'get',
        async:true,
        dataType:'json',
        success:function(result){
            let code=result.code;
            let msg=result.msg;
            msg = msg === 'ok' ? '操作成功' : msg;
            let returndata=result.data;
            let url=result.url;
            if(code){
                if(success_callback){
                    success_callback(msg,returndata,url);//回调函数
                }else{
                    layer.msg(msg, {time: 500}, function (){
                        if(url){
                            window.location.href=url;
                        }else{
                            location.reload();
                        }
                    });
                }
            }else{
                if(error_callback){
                    error_callback(msg,returndata,url);//回调函数
                }else{
                    layer.alert(msg);
                }

            }
        },
        error:function(xhr,textStatus){
            alert("程序出错，请联系管理员");
            layer.close(index);//关闭加载气泡提示
        },
        complete:function(){
            layer.close(index);//关闭加载气泡提示
        }
    })
}

/**
 * 多选操作
 * @param ajax_url
 * @param data
 * @param success_callback
 * @param error_callback
 */
function multiple_del(ajax_url,data,success_callback,error_callback){
    let index=layer.load(0,{time:100000});//加载气泡提示
    $.ajax({
        url:ajax_url,
        type:'post',
        async:true,
        dataType:'json',
        data: data,
        success:function(result){
            let code=result.code;
            let msg=result.msg;
            msg = msg === 'ok' ? '操作成功' : msg;
            let returndata=result.data;
            let url=result.url;
            if(code){
                if(success_callback){
                    success_callback(msg,returndata,url);//回调函数
                }else{
                    layer.msg(msg, {time: 500}, function (){
                        if(url){
                            window.location.href=url;
                        }else{
                            location.reload();
                        }
                    });
                }
            }else{
                if(error_callback){
                    error_callback(msg,returndata,url);//回调函数
                }else{
                    layer.alert(msg);
                }

            }
        },
        error:function(xhr,textStatus){
            alert("程序出错，请联系管理员");
            layer.close(index);//关闭加载气泡提示
        },
        complete:function(){
            layer.close(index);//关闭加载气泡提示
        }
    })
}





//返回上个页面
function goback(url){
    if(url){
        window.location.href=url;
    }else{
        window.location.href=document.referrer;
    }
}
//取消并返回上个页面
function cancel(url){
    if(url){
        window.location.href=url;
    }else{
        window.location.href=document.referrer;
    }
}

//ajax del
$(function(){
    $(".multiple_del").click(function(){
        let url=$(this).data("href") ? $(this).data("href") :  $(this).attr("href");
        let id = getCheckedIds();
        if(id.length === 0){
            layer.alert('没有选中的数据');
            return false;
        }
        let data = {id: id};
        let msg=$(this).data("msg");
        if(!msg){
            msg="您确定要批量删除吗？";
        }
        layer.confirm(msg,function(){
            multiple_del(url, data);
        });
        return false;
    })

    $(".ajax_del").click(function(){
        let url=$(this).data("href") ? $(this).data("href") :  $(this).attr("href");
        let msg=$(this).data("msg");
        if(!msg){
            msg="您确定要删除吗？";
        }
        layer.confirm(msg,function(){
            ajax_del(url);
        });
        return false;
    })
    $(".goback,.back,.cancel").click(function(){
        goback();
    })
    //tips层
    $(".tips").click(function(){
        let title=$(this).attr("title");
        layer.tips(title, this, {
            tips: [1],
            time: 10000
        });
    })
    //全选
    $(".checkall").click(function(){
        let y=$(this).val();//alert(y);
        if(y==0){
            $(".chekboxs").prop("checked", true)
            y=1;
        }else if(y==1){
            $(".chekboxs").prop("checked", false)
            y=0;
        }
        $(".checkall").val(y);
        //disabled不让选中（哪怕选中也不会提交数据，这里主要是增加用户体验）
        $(":disabled").prop("checked", false)
    });

})


//layer iframe插件
$(function(){
    $(".zframe").click(function(){
        let url=$(this).data("href") ?  $(this).data("href") :  $(this).attr("href");
        let title=$(this).data("title") ? $(this).data("title") : $(this).attr("title") ;
        let width=$(this).data("width");
        let height=$(this).data("height");
        let maxmin=$(this).data("maxmin");
        let id = getCheckedIds();
        if(id.length === 0){
            layer.alert('没有选中的数据');
            return false;
        }
        if(id.length !== 1){
            layer.alert('不能多选，请选择一个数据');
            return false;
        }
        url = url + '?id=' + id[0];
        iframe(url,width,height,title,maxmin);
        return false;
    });
})


//layer iframe插件
$(function(){
    $(".iframe").click(function(){
        let url=$(this).data("href") ?  $(this).data("href") :  $(this).attr("href");
        let title=$(this).data("title") ? $(this).data("title") : $(this).attr("title") ;
        let width=$(this).data("width");
        let height=$(this).data("height");
        let maxmin=$(this).data("maxmin");
        iframe(url,width,height,title,maxmin);
        return false;
    });
})
//通过框架打开页面
function iframe(url,w,h,title,maxmin = true,refresh = false){
    let width=w?w:"600px";
    let height=h?h:"600px";
    let load_index =layer.load(0,{time:100000});//加载气泡提示
    let index=layer.open({
        type: 2,
        title: title,
        area: [width,height],
        fixed: false, //不固定
        moveOut: true,
        // maxmin: maxmin,
        content: [url],
        cancel: function (){
            if(refresh){
                window.location.reload()
            }
        },
        success: function(layero){

            let top = $(layero).css('top');
            let top_px = 0;
            let left_px = 0;
            if( parseInt(top) < 0){
                if(width !== '100%'){
                    left_px = '15px';
                }
                if(height !== '100%'){
                    top_px = '15px';
                }
                layer.style(index, {
                    top: top_px,
                    left: left_px
                });
            }

            if(!title){
                iframeTitle=window.frames["layui-layer-iframe"+index].document.title;
                if(iframeTitle){
                    $("#layui-layer"+index).find(".layui-layer-title").html(iframeTitle);
                }
            }
            //如果没有声明高度则框架高度自动
            if(!h){
                layer.iframeAuto(index);
            }
            setTimeout(function (){
                layer.close(load_index);
            }, 100)

        }
    });

}

$(function (){
    //关闭iframe窗口页面
    $('.close').click(function(){
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(index);
    });
})

// js创建含数字字母的随机字符串
function randStr() {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for (var i = 0; i < 10; i++)
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    return text;
}

/**
 * 获取列表选中的id
 */
function getCheckedIds(){
    let ids = [];
    let data = $('form.layui-form').serializeArray();
    for(let i in data){
        if(data[i]['name'] == 'ids[]'){
            ids.push(parseInt(data[i]['value']));
        }
    }
    return ids;
}
